package com.un.ebs.core.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.Map;

/**
 * @email 496382223@qq.com
 * @author:Lijj
 * @date: 2019/7/25
 */
public class JwtUtils {
    private static final String SECRET = "websstoken";

    /**
     * 创建token
     *
     * @param claim claim中为userId
     * @return token
     */
    public static String createToken(String subject, Map claim) {
        //按分钟算
        long expirationDate = 60 * 12;
        return createToken(subject, claim, expirationDate);
    }

    public static String createToken(String subject, Map claim, long exp) {
        LocalDateTime nowTime = LocalDateTime.now();
        if (exp <= 0) {
            return Jwts.builder().setClaims(claim)
                    .setSubject(subject) //设置token主题
                    .setIssuedAt(localDateTimeToDate(nowTime)) //设置token发布时间
                    .signWith(SignatureAlgorithm.HS512, SECRET)
                    .compact();
        } else {
            return Jwts.builder().setClaims(claim)
                    .setSubject(subject) //设置token主题
                    .setIssuedAt(localDateTimeToDate(nowTime)) //设置token发布时间
                    .setExpiration(getExpirationDate(nowTime, exp)) // 设置token过期时间
                    .signWith(SignatureAlgorithm.HS512, SECRET)
                    .compact();
        }

    }

    /**
     * 将LocalDateTime转换为Date
     *
     * @param localDateTime
     * @return Date
     */
    public static Date localDateTimeToDate(LocalDateTime localDateTime) {
        ZoneId zoneId = ZoneId.systemDefault();
        ZonedDateTime zdt = localDateTime.atZone(zoneId);
        return Date.from(zdt.toInstant());
    }

    /**
     * 获取token过期的时间
     *
     * @param createTime       token创建时间
     * @param calendarInterval token有效时间间隔
     * @return
     */
    public static Date getExpirationDate(LocalDateTime createTime, long calendarInterval) {
        LocalDateTime expirationDate = createTime.plus(calendarInterval, ChronoUnit.MINUTES);
        return localDateTimeToDate(expirationDate);
    }


    /**
     * JWT  解析token是否正确
     *
     * @param token
     * @return
     * @throws Exception
     */
    public static Claims parseToken(String token) throws ExpiredJwtException {

        Claims claims = Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getBody();
        return claims;

    }
}
